//
//  ViewController.m
//  faceLooker
//
//  Created by yww on 2018/12/12.
//  Copyright © 2018年 yww. All rights reserved.
//

#import "ViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"

//说明
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>{
    UITableView *tableView;
    BOOL colorChange;
}
@property(nonatomic,copy)NSString *str;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)NSTimer *changeTimer;
@end
static NSString *identifier = @"mycell";
@implementation ViewController
/*
- (NSTimer *)changeTimer{
    if (!_changeTimer) {
        _changeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeCellContent) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_changeTimer forMode: NSRunLoopCommonModes];
    }
    return _changeTimer;
}
 */
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //开启定时器
    [self.changeTimer setFireDate:[NSDate distantPast]];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //关闭定时器
    [self.changeTimer setFireDate:[NSDate distantFuture]];
}

- (void)dealloc{
    [self.changeTimer didChangeValueForKey:@"renao"];
    //关闭定时器
    self.changeTimer = nil;
    [self.changeTimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    tableView.backgroundColor = [UIColor clearColor];
    tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.fd_debugLogEnabled = YES;//允许debug
    [self.view addSubview:tableView];
    
    //添加tableviewheadview
    UIView *headeView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    headeView.backgroundColor = [UIColor whiteColor];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth-300)/2.0, 41, 300, 1)];
    line.backgroundColor = [UIColor redColor];
    CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    colorAnimation.duration  = 1.2;
    colorAnimation.beginTime = 0.00;
    colorAnimation.repeatCount = MAXFLOAT;
    colorAnimation.fromValue = (id)randomColor.CGColor;
    colorAnimation.toValue = (id)randomColor.CGColor;
    [line.layer addAnimation:colorAnimation forKey:@"lineColor"];
    [headeView addSubview:line];
    
    // 添加一个加载动画
    NSInteger num = 12;
    for (int i = 0; i <num; i++) {
        UIView *point = [[UIView alloc]initWithFrame:CGRectMake((ScreenWidth-173)/2.0+15*i,38, 6, 6)];
        point.layer.cornerRadius = 3;
        point.tag = i;
        point.clipsToBounds = YES;
        point.backgroundColor = randomColor;
        
        //重用机制如何用
        CAAnimationGroup *grup =  [self jump:num*0.1 Y:@(16)];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((i+1)*0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [point.layer addAnimation:grup forKey:@"jump"];
        });
        [headeView addSubview:point];
    }
    tableView.tableHeaderView = headeView;
    
    //注册cell
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier];
    //请求数据
    [self getData];
    
}
//改变内容
- (void)changeCellContent{
//    [tableView reloadData];
}

- (void)getData{
    if (self.dataArr.count >25) {
        return;
    }
    if (self.dataArr.count == 0) {
         [MBProgressHUD showMessag:@"加载中..." toView:self.view hideState:NO];
    }
    [FLHttpCommunicate GET:@"https://api.gushi.ci/all" parameters:nil dictBlock:^(NSDictionary *dict) {
        NSLog(@"结果==%@  ",dict);
        [self.dataArr addObject:dict];
        NSLog(@"个数== %ld",self.dataArr.count);
        if (self.dataArr.count == 25) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [tableView reloadData];
            });
        }
        [self getData];
        
    } errorBlock:^(NSError *error) {
        [tableView reloadData];
        return ;
        //[MBProgressHUD showError:@"出现错误" toView:self.view];
    }];
    
}


- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

-(NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        //很不满意
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        [self configureCell:cell atIndexPath:indexPath];
    }
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
    cell.textLabel.numberOfLines = 0;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.textColor = [UIColor darkGrayColor];
    
    NSDictionary *dict = self.dataArr[indexPath.row];
    NSString*author = dict[@"author"];//作者
    NSInteger authorL = author.length;
    NSString*content = dict[@"content"];//类容
    NSString*origin = dict[@"origin"];//词牌名 名称
    NSInteger originL = origin.length;
    NSString *result = [NSString stringWithFormat:@"《%@》.%@\n\n%@\n\n",origin,author,content];
    NSMutableAttributedString *mutableStr = [[NSMutableAttributedString alloc]initWithString:result];
    [mutableStr addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0,  originL+3+authorL)];
    [mutableStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0,  originL+3+authorL)];
    cell.textLabel.attributedText = mutableStr;
//    NSLog(@"str ======%@",result);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView fd_heightForCellWithIdentifier:identifier configuration:^(UITableViewCell *cell) {
        [self configureCell:cell atIndexPath:indexPath];
    }];
}
- (CAAnimationGroup *)jump:(float)time Y:(NSNumber *)y {
    /* 动画1（在X轴方向移动） */
    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    // 终点设定 0.2s
    animation1.fromValue = @(0);
    animation1.toValue = @(-[y floatValue]); // 終点
    animation1.duration = 0.05;
    animation1.beginTime = 0.00;
    CABasicAnimation *colorAnimation1 = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    colorAnimation1.duration  = 0.6;
    colorAnimation1.beginTime = 0.00;
    colorAnimation1.fromValue = (id)[UIColor redColor].CGColor;
    colorAnimation1.toValue = (id)[UIColor blackColor].CGColor;
    
    /* 动画1（在X轴方向移动） */
    CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    // 终点设定
    animation2.fromValue = @(-[y floatValue]);
    animation2.toValue = 0; // 終点
    animation2.duration = 0.05;
    animation2.beginTime = 0.05;
    
    CABasicAnimation *colorAnimation2 = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
    colorAnimation2.duration  = 0.05;
    colorAnimation2.beginTime = 0.05;
    colorAnimation2.fromValue = (id)randomColor.CGColor;
    colorAnimation2.toValue = (id)randomColor.CGColor;
    
    /* 动画组 */
    CAAnimationGroup *group = [CAAnimationGroup animation];
    // 动画选项设定
    group.duration = time;
    group.repeatCount = MAXFLOAT;
    group.removedOnCompletion = NO;
    // 添加动画
    group.animations = [NSArray arrayWithObjects:animation1,colorAnimation1, animation2, nil];
    return group;
}

@end


 
